package com.zangchat.service.impl;

import com.alibaba.fastjson.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.common.core.domain.AjaxResult;
import com.zangchat.domain.ChatUsers;
import com.zangchat.service.IChatUsersService;
import com.zangchat.service.ISmsService;
import com.zangchat.utils.HttpUtil;
import com.common.utils.security.Md5Utils;
import com.zangchat.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by GaoTing on 2019/4/29
 * Explain:自定义 服务层实现 .处理一些特殊接口
 */
@Service
public class SmsServiceImpl implements ISmsService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
   private IChatUsersService chatUsersService;

    /**
     * 发送短信验证码
     *
     * @param phone   手机号
     * @param request
     * @param type    类型 1 注册 2修改密码 3修改手机号原手机号码 4修改手机号码新手机号
     * @return
     */

    @Override
    public AjaxResult sendCode(String phone, HttpServletRequest request, String type) {
        if ("".equals(phone) || phone == null) {
            return AjaxResult.error("请输入手机号");
        }
        ChatUsers checkuserPhoneChatUsers=new ChatUsers();
        checkuserPhoneChatUsers.setUserPhone(phone);
        QueryWrapper<ChatUsers> queryWrapper=new QueryWrapper<>(checkuserPhoneChatUsers);
        BaseMapper<ChatUsers> baseMapper = chatUsersService.getBaseMapper();
        ChatUsers chatUsers = baseMapper.selectOne(queryWrapper);
        int i=0;
        if (chatUsers!=null){
            i=1;
        }
        if ("1".equals(type) || "4".equals(type)) {//1 注册或 4修改手机号新手机号
            if (i==1){
                return AjaxResult.error("该手机号已经注册");
            }
        }
        if ("2".equals(type) || "3".equals(type)) { //2忘记密码 或3更换手机号原手机号
            if (i==0) {
                return AjaxResult.error("该手机号尚未注册");
            }
        }
        String fnc = "default";
//        if (StringUtils.isEmpty(fnc)){
////            fnc="default";
////        }
//		if(cacheUtil.isKeyInCache(phone)){
//			resultMap.put("code","00");
//			resultMap.put("msg","请不要重复发送");
//			return  resultMap;
//		}
        String ip = request.getServerName();
        JSONObject jsonObject = this.send_register_message(phone, ip, fnc, type);
        String cod = jsonObject.get("cod").toString();
        Integer code = Integer.parseInt(cod);
        if (code <= 0) {
            return AjaxResult.error("手机号发送频繁，请1小时后再试");
        }
//        cacheUtil.set(phone, code);
        return AjaxResult.success("验证码发送成功,请注意查收", code);
    }

    /**
     * 校验短息验证码
     *
     * @param userPhone 手机号
     * @param smsCode   验证码
     * @param type      类型 1 注册 2设置和忘记密码 3修改手机号原手机号码 4修改手机号码新手机号
     * @return
     */
    @Override
    public AjaxResult checkCode(String userPhone, String smsCode, String type) {
        if ("".equals(userPhone) || userPhone == null) {
            return AjaxResult.error("请输入手机号");
        }
        if ("".equals(smsCode) || smsCode == null) {
            return AjaxResult.error("验证码不能为空，请输入验证码");
        }
        String typeFlag = "";
        if ("1".equals(type)) {//注册
            typeFlag = "addUser";
        }
        if ("2".equals(type)) { //修改密码
            typeFlag = "updatePassword";
        }
        if ("3".equals(type) || "4".equals(type)) {//3修改手机号原手机号码
            typeFlag = "updatePhone";
        }
        String key = Md5Utils.hash("zangchat" + userPhone + typeFlag);

        if (!redisUtil.isKeyInCache(key)) {
            return AjaxResult.error("验证超时，请输重新获取验证码");
        }
        String cacheUtilCode = redisUtil.get(key).toString();
        if (!smsCode.equals(cacheUtilCode)) {
            return AjaxResult.error("验证码有误，请重新输入");
        }
//        redisUtil.remove(key);
        return AjaxResult.success("验证码校验通过");
    }

    /**
     * 实际执行的发送短信验证码方法
     *
     * @param number 手机号
     * @param ip
     * @param fnc
     * @param type   类型 1 注册 2修改密码 3修改手机号原手机号码 4修改手机号码新手机号
     * @return
     */
    public JSONObject send_register_message(String number, String ip, String fnc, String type) {

        if (!notSend(number)){
            //获取发送状态
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cod", -1);
            return jsonObject;
        }

        //随机生成六位验证码
//        String code = Tools.getRandomNum(6);
        int code = (int)((Math.random()*9+1)*1000);
        //发送的短信内容
//		String content="您的注册验证码为"+code+",如非本人操作,请忽略此信息.【共享商城】";
        String content = null;
        String typeFlag = "";
        if ("1".equals(type)) {
            typeFlag = "addUser";
            content = "您的注册验证码为" + code + ",如非本人操作,请忽略此信息.【企乐网】";
        }
        if ("2".equals(type)) {
            typeFlag = "updatePassword";
            content = "您的验证码为" + code + ",此验证码为修改密码验证码,如非本人操作,请忽略此信息.【企乐网】";
        }
        if ("3".equals(type) || "4".equals(type)) {
            content = "您的验证码为" + code + ",验证码为修改手机号验证码,如非本人操作,请忽略此信息.【企乐网】";
            typeFlag = "updatePhone";
        }

        Object o = this.sendSMS(number, content);
        String resultCode = o.toString().substring(0, 2);
        if (resultCode.equals("-1")) {
            //获取发送状态
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cod", -1);
        }
        if (resultCode.equals("-5")) {
            //获取发送状态
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cod", -1);
        }
        //获取发送状态
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cod", code);//返回验证码
//        jsonObject.put("cod","1234");//返回验证码
        /**
         * 先判断缓存中有没有手机号对应的值，
         * 如果有更新值
         * 如果有添加值
         */
        String key = Md5Utils.hash("zangchat" + number + typeFlag);
        if (redisUtil.isKeyInCache(key)) {
            redisUtil.update(key, code+"", 3000L);
        } else {
            redisUtil.set(key, code+"", 3000L);
        }
        ;
//		cacheUtil.set(number,code,300L);
        /**
         * 存入短信记录表
         */
        return jsonObject;
    }

    public Object sendSMS(String mobile, String content) {
        Map<String, Object> map = new HashMap<>();
//        map.put("CorpID", "QLW008624");
        map.put("CorpID", "QLW008908");
        map.put("Pwd", "zm0513@");
        map.put("Mobile", mobile);
        map.put("Content", content);
        String url = "https://sdk2.028lk.com/sdk2/BatchSend2.aspx";
        return HttpUtil.doPost(url, map);
    }


    public boolean notSend(String mobile){
        Map<String, Object> map = new HashMap<>();
//        map.put("CorpID", "QLW008624");
        map.put("CorpID", "QLW008908");
        map.put("Pwd", "zm0513@");
        String url = "https://sdk2.028lk.com/sdk2/NotSend.aspx";
        String result = HttpUtil.doPost(url, map);
        if (result.indexOf(mobile)>-1){
            return false;
        }
        return true;
    }



    public static void main(String[] args) {
        SmsServiceImpl smsService=new SmsServiceImpl();
        Object o = smsService.send_register_message("15690345228","192.168.1.10","1","1");
        System.out.println(o.toString()+":是返回的数据");
    }

}
